<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品分类管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>商品分类管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal">
            新增分类
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-6">
                <input type="text" id="searchName" class="form-control" placeholder="输入分类名称搜索">
            </div>
            <div class="col-md-3">
                <select id="searchParentId" class="form-select">
                    <option value="">全部父分类</option>
                    <option value="0">顶级分类</option>
                </select>
            </div>
            <div class="col-md-3">
                <button class="btn btn-success w-100" onclick="queryCategoryList(1)">搜索</button>
            </div>
        </div>
    </div>

    <!-- 分类列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>分类ID</th>
                    <th>分类名称</th>
                    <th>父分类</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="categoryTableBody">
                <tr><td colspan="6" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑分类弹窗 -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="categoryForm">
                    <input type="hidden" id="categoryId">
                    <div class="mb-3">
                        <label for="categoryName" class="form-label">分类名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="categoryName" required placeholder="请输入分类名称">
                    </div>
                    <div class="mb-3">
                        <label for="parentId" class="form-label">父分类 <span class="text-danger">*</span></label>
                        <select class="form-select" id="parentId" required>
                            <option value="0">顶级分类（无父分类）</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveCategory()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    // 页面加载初始化
    window.onload = function () {
        loadParentCategories();
        queryCategoryList(currentPage);
    };

    // 加载父分类列表（用于下拉选择）
    async function loadParentCategories() {
        try {
            const res = await axios.get("/api/categories/all");
            const categories = res.data;
            const parentIdSelect = document.getElementById("parentId");
            const searchParentIdSelect = document.getElementById("searchParentId");

            categories.forEach(cat => {
                if (cat.parentId === 0) { // 只加载顶级分类作为父分类选项
                    parentIdSelect.innerHTML += `<option value="${cat.categoryId}">${cat.categoryName}</option>`;
                    searchParentIdSelect.innerHTML += `<option value="${cat.categoryId}">${cat.categoryName}</option>`;
                }
            });
        } catch (err) {
            Common.errorMsg("加载父分类失败：" + err.message);
        }
    }

    // 查询分类列表
    async function queryCategoryList(pageNum) {
        try {
            const categoryName = document.getElementById("searchName").value;
            const parentId = document.getElementById("searchParentId").value;

            const res = await axios.get("/api/categories/page", {
                params: {
                    pageNum,
                    pageSize,
                    categoryName,
                    parentId: parentId || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("categoryTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(cat => {
                const parentName = cat.parentId === 0 ? "无（顶级分类）" : cat.parentCategory?.categoryName || "未知";
                const row = `
                        <tr>
                            <td>${cat.categoryId}</td>
                            <td>${cat.categoryName}</td>
                            <td>${parentName}</td>
                            <td>${Common.formatDate(cat.createTime)}</td>
                            <td>${Common.formatDate(cat.updateTime)}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editCategory(${cat.categoryId})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteCategory(${cat.categoryId})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryCategoryList);
        } catch (err) {
            Common.errorMsg("查询分类失败：" + err.message);
            document.getElementById("categoryTableBody").innerHTML = '<tr><td colspan="6" class="text-center">查询失败</td></tr>';
        }
    }

    // 编辑分类
    async function editCategory(categoryId) {
        try {
            const res = await axios.get(`/api/categories/${categoryId}`);
            const cat = res.data;

            document.getElementById("categoryId").value = cat.categoryId;
            document.getElementById("categoryName").value = cat.categoryName;
            document.getElementById("parentId").value = cat.parentId;
            document.getElementById("modalTitle").textContent = "编辑分类";

            new bootstrap.Modal(document.getElementById("categoryModal")).show();
        } catch (err) {
            Common.errorMsg("加载分类信息失败：" + err.message);
        }
    }

    // 保存分类（新增/编辑）
    async function saveCategory() {
        const categoryName = document.getElementById("categoryName").value;
        const parentId = document.getElementById("parentId").value;
        const categoryId = document.getElementById("categoryId").value;

        if (!categoryName) {
            Common.errorMsg("请输入分类名称！");
            return;
        }

        const categoryData = {
            categoryName,
            parentId: parseInt(parentId)
        };

        try {
            if (categoryId) {
                // 编辑
                categoryData.categoryId = parseInt(categoryId);
                await axios.put("/api/categories", categoryData);
                Common.successMsg("编辑分类成功！");
            } else {
                // 新增
                await axios.post("/api/categories", categoryData);
                Common.successMsg("新增分类成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("categoryModal")).hide();
            queryCategoryList(currentPage);
            document.getElementById("categoryForm").reset();
            document.getElementById("categoryId").value = "";
            document.getElementById("modalTitle").textContent = "新增分类";
        } catch (err) {
            Common.errorMsg("保存分类失败：" + err.message);
        }
    }

    // 删除分类
    function deleteCategory(categoryId) {
        Common.confirmMsg("确定要删除该分类吗？删除后子分类可能受影响！", async () => {
            try {
                await axios.delete(`/api/categories/${categoryId}`);
                Common.successMsg("删除分类成功！");
                queryCategoryList(currentPage);
            } catch (err) {
                Common.errorMsg("删除分类失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>